<template>
  <div class="page-container">
    <header class="header">
      <BackBtn />
      <h1>修改用户信息</h1>
      <Time />
    </header>

    <!-- 主要内容区域 -->
    <div class="main-content" v-loading="loading" element-loading-text="加载中..."
      :element-loading-background="'rgba(0, 0, 0, 0)'">
      <div class="edit-form">
        <!-- 基本信息展示 -->
        <div class="basic-info">
          <div class="info-item">
            <span>ID: </span>
            <span>{{ basicInfo.id }}</span>
          </div>
          <div class="info-item">
            <span>注册日期: </span>
            <span>{{ basicInfo.registrationTime }}</span>
          </div>
          <div class="info-item">
            <span>来源: </span>
            <span>{{ basicInfo.source }}</span>
          </div>
        </div>

        <!-- 表单内容 -->
        <el-form :model="formData" label-width="100px" class="form-content">
          <div class="form-row">
            <el-form-item label="姓名:">
              <el-input v-model="formData.uname" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="所属单位:">
              <el-input v-model="formData.unit" placeholder="请输入所属单位" />
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="性别:">
              <el-select v-model="formData.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
            <el-form-item label="身份:">
              <el-select v-model="formData.identity" placeholder="请选择身份">
                <el-option label="第十一届政协委员" value="第十一届政协委员" />
                <el-option label="第十届政协委员" value="第十届政协委员" />
                <el-option label="第九届政协委员" value="第九届政协委员" />
                <el-option label="联络员" value="联络员" />
                <el-option label="工作人员" value="工作人员" />
              </el-select>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="民族:">
              <el-select v-model="formData.ethnicity" placeholder="请选择民族">
                <el-option label="汉族" value="汉族" />
                <el-option label="蒙古族" value="蒙古族" />
                <el-option label="回族" value="回族" />
                <el-option label="藏族" value="藏族" />
                <el-option label="维吾尔族" value="维吾尔族" />
                <el-option label="苗族" value="苗族" />
                <el-option label="彝族" value="彝族" />
                <el-option label="壮族" value="壮族" />
                <el-option label="布依族" value="布依族" />
                <el-option label="朝鲜族" value="朝鲜族" />
                <el-option label="满族" value="满族" />
                <el-option label="侗族" value="侗族" />
                <el-option label="瑶族" value="瑶族" />
                <el-option label="白族" value="白族" />
                <el-option label="土家族" value="土家族" />
                <el-option label="哈尼族" value="哈尼族" />
                <el-option label="哈萨克族" value="哈萨克族" />
                <el-option label="傣族" value="傣族" />
                <el-option label="黎族" value="黎族" />
                <el-option label="傈僳族" value="傈僳族" />
                <el-option label="佤族" value="佤族" />
                <el-option label="畲族" value="畲族" />
                <el-option label="高山族" value="高山族" />
                <el-option label="拉祜族" value="拉祜族" />
                <el-option label="水族" value="水族" />
                <el-option label="东乡族" value="东乡族" />
                <el-option label="纳西族" value="纳西族" />
                <el-option label="景颇族" value="景颇族" />
                <el-option label="柯尔克孜族" value="柯尔克孜族" />
                <el-option label="土族" value="土族" />
                <el-option label="达斡尔族" value="达斡尔族" />
                <el-option label="仫佬族" value="仫佬族" />
                <el-option label="羌族" value="羌族" />
                <el-option label="布朗族" value="布朗族" />
                <el-option label="撒拉族" value="撒拉族" />
                <el-option label="毛南族" value="毛南族" />
                <el-option label="仡佬族" value="仡佬族" />
                <el-option label="锡伯族" value="锡伯族" />
                <el-option label="阿昌族" value="阿昌族" />
                <el-option label="普米族" value="普米族" />
                <el-option label="塔吉克族" value="塔吉克族" />
                <el-option label="怒族" value="怒族" />
                <el-option label="乌孜别克族" value="乌孜别克族" />
                <el-option label="俄罗斯族" value="俄罗斯族" />
                <el-option label="鄂温克族" value="鄂温克族" />
                <el-option label="德昂族" value="德昂族" />
                <el-option label="保安族" value="保安族" />
                <el-option label="裕固族" value="裕固族" />
                <el-option label="京族" value="京族" />
                <el-option label="塔塔尔族" value="塔塔尔族" />
                <el-option label="独龙族" value="独龙族" />
                <el-option label="鄂伦春族" value="鄂伦春族" />
                <el-option label="赫哲族" value="赫哲族" />
                <el-option label="门巴族" value="门巴族" />
                <el-option label="珞巴族" value="珞巴族" />
                <el-option label="基诺族" value="基诺族" />
              </el-select>
            </el-form-item>
            <el-form-item label="界别:">
              <el-select v-model="formData.affiliation" placeholder="请选择界别">
                <el-option label="中国共产党" value="中国共产党" />
                <el-option label="中国国民党革命委员会（民革）" value="中国国民党革命委员会（民革）" />
                <el-option label="中国民主同盟（民盟）" value="中国民主同盟（民盟）" />
                <el-option label="中国民主建国会（民建）" value="中国民主建国会（民建）" />
                <el-option label="中国民主促进会（民进）" value="中国民主促进会（民进）" />
                <el-option label="中国农工民主党" value="中国农工民主党" />
                <el-option label="中国致公党" value="中国致公党" />
                <el-option label="九三学社" value="九三学社" />
                <el-option label="台湾民主自治同盟（台盟）" value="台湾民主自治同盟（台盟）" />
                <el-option label="无党派人士" value="无党派人士" />
                <el-option label="中国共产主义青年团" value="中国共产主义青年团" />
                <el-option label="中华全国总工会" value="中华全国总工会" />
                <el-option label="中华全国妇女联合会" value="中华全国妇女联合会" />
                <el-option label="中华全国青年联合会" value="中华全国青年联合会" />
                <el-option label="中华全国工商业联合会" value="中华全国工商业联合会" />
                <el-option label="科学技术界" value="科学技术界" />
                <el-option label="社会科学界" value="社会科学界" />
                <el-option label="经济界" value="经济界" />
                <el-option label="农业界" value="农业界" />
                <el-option label="教育界" value="教育界" />
                <el-option label="体育界" value="体育界" />
                <el-option label="新闻出版界" value="新闻出版界" />
                <el-option label="医药卫生界" value="医药卫生界" />
                <el-option label="对外友好界" value="对外友好界" />
                <el-option label="社会福利和社会保障界" value="社会福利和社会保障界" />
                <el-option label="文化艺术界" value="文化艺术界" />
                <el-option label="科学技术协会" value="科学技术协会" />
                <el-option label="少数民族界" value="少数民族界" />
                <el-option label="宗教界" value="宗教界" />
                <el-option label="台湾同胞联谊会" value="台湾同胞联谊会" />
                <el-option label="港澳同胞（香港、澳门代表）" value="港澳同胞（香港、澳门代表）" />
                <el-option label="特邀香港人士" value="特邀香港人士" />
                <el-option label="特邀澳门人士" value="特邀澳门人士" />
                <el-option label="特别邀请人士" value="特别邀请人士" />
                <el-option label="环境资源界" value="环境资源界" />
              </el-select>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="出生日期:">
              <el-date-picker v-model="formData.birthDate" type="date" placeholder="请选择出生日期" format="YYYY年MM月DD日" />
            </el-form-item>
            <el-form-item label="地区:">
              <el-select v-model="formData.region" placeholder="请选择地区">
                <el-option label="张家畔街道" value="张家畔街道" />
                <el-option label="东坑镇" value="东坑镇" />
                <el-option label="周河镇" value="周河镇" />
                <el-option label="天赐湾镇" value="天赐湾镇" />
                <el-option label="镇靖镇" value="镇靖镇" />
                <el-option label="海则滩镇" value="海则滩镇" />
                <el-option label="中山涧镇" value="中山涧镇" />
                <el-option label="龙洲镇" value="龙洲镇" />
                <el-option label="黄蒿界镇" value="黄蒿界镇" />
                <el-option label="红墩界镇" value="红墩界镇" />
                <el-option label="王渠则镇" value="王渠则镇" />
                <el-option label="杨米涧镇" value="杨米涧镇" />
                <el-option label="杨桥畔镇" value="杨桥畔镇" />
                <el-option label="席麻湾镇" value="席麻湾镇" />
                <el-option label="宁条梁镇" value="宁条梁镇" />
                <el-option label="高家堡镇" value="高家堡镇" />
                <el-option label="新桥镇" value="新桥镇" />
              </el-select>
            </el-form-item>

          </div>

          <div class="form-row">
            <el-form-item label="通信地址:">
              <el-input v-model="formData.address" placeholder="请输入通信地址" />
            </el-form-item>
            <el-form-item label="邮政编码:">
              <el-input v-model="formData.postalCode" placeholder="请输入邮政编码" />
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="手机号:">
              <el-input v-model="formData.phone" placeholder="请输入手机号" disabled />
            </el-form-item>
          </div>


          <!-- 密码重置表单 -->
          <div class="form-row" v-if="showPasswordReset">
            <el-form-item label="新密码:">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码:">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
          </div>
        </el-form>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="handleBack">返 回</el-button>
          <el-button type="danger" @click="handleConfirm"
            :disabled="userStatus === '已驳回' || userStatus === '已注销'">确定修改</el-button>
          <el-button type="danger" @click="handleResetPassword" :class="{ 'active': showPasswordReset }"
            :disabled="userStatus === '已驳回' || userStatus === '已注销'">
            {{ showPasswordReset ? '取消重置' : '重设密码' }}
          </el-button>
          <el-button v-if="showPasswordReset" type="success" @click="confirmResetPassword"
            :disabled="userStatus === '已驳回' || userStatus === '已注销'">
            确认重置
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserDetail, updateUser, resetPassword } from '@/api/admin'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
const loading = ref(false)
const router = useRouter()
const route = useRoute()

// 表单数据
const formData = ref({
  uname: '',
  unit: '',
  gender: '',
  identity: '',
  ethnicity: '',
  affiliation: '',
  birthDate: '',
  region: '',
  phone: '',
  reservedInfo: '',
  address: '',
  postalCode: ''
})

// 基本信息
const basicInfo = ref({
  id: '',
  registrationTime: '',
  source: '注册'
})

// 用户状态
const userStatus = ref('')

// 密码重置相关
const showPasswordReset = ref(false)
const passwordForm = ref({
  newPassword: '',
  confirmPassword: ''
})

// 获取用户详情
const fetchUserDetail = async () => {
  try {
    const uid = route.query.uid
    if (!uid) {
      ElMessage.error('用户ID不存在')
      return
    }

    const res = await getUserDetail(uid)
    if (res.code === 200) {
      const userInfo = res.data
      // 更新表单数据
      formData.value = {
        uname: userInfo.uname || '',
        unit: userInfo.unit || '',
        gender: userInfo.gender || '',
        identity: userInfo.identity || '',
        ethnicity: userInfo.ethnicity || '',
        affiliation: userInfo.affiliation || '',
        birthDate: userInfo.birthDate || '',
        region: userInfo.region || '',
        phone: userInfo.phone || '',
        reservedInfo: userInfo.reservedInfo || '',
        address: userInfo.address || '',
        postalCode: userInfo.postalCode || ''
      }

      // 更新基本信息
      basicInfo.value = {
        id: userInfo.uid || '',
        registrationTime: userInfo.registrationTime || '',
        source: '注册'
      }

      // 保存用户状态
      userStatus.value = userInfo.status || ''
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 检查用户是否可以修改
const isUserEditable = () => {
  if (userStatus.value === '已驳回' || userStatus.value === '已注销') {
    const message = userStatus.value === '已驳回' ? '该用户已驳回，无法修改' : '该用户已注销，无法修改'
    ElMessage.warning(message)
    return false
  }
  return true
}

// 确认修改
const handleConfirm = async () => {
  // 先检查用户状态
  if (!isUserEditable()) return

  try {
    const uid = route.query.uid
    if (!uid) {
      ElMessage.error('用户ID不存在')
      return
    }

    const response = await updateUser({
      uid,
      ...formData.value
    })

    if (response.code === 200) {
      ElMessage.success('修改成功')
      fetchUserDetail()
    } else {
      ElMessage.error(response.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('修改失败')
  }
}

// 重设密码
const handleResetPassword = () => {
  // 先检查用户状态
  if (!isUserEditable()) return

  showPasswordReset.value = !showPasswordReset.value
  if (!showPasswordReset.value) {
    passwordForm.value = {
      newPassword: '',
      confirmPassword: ''
    }
  }
}

const confirmResetPassword = async () => {
  if (!passwordForm.value.newPassword) {
    ElMessage.warning('请输入新密码')
    return
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  if (passwordForm.value.newPassword.length < 6) {
    ElMessage.warning('密码长度不能少于6位')
    return
  }

  try {
    const uid = route.query.uid
    const res = await resetPassword(uid, passwordForm.value.newPassword)
    if (res.code === 200) {
      ElMessage.success('密码重置成功')
      showPasswordReset.value = false
      passwordForm.value = {
        newPassword: '',
        confirmPassword: ''
      }
    } else {
      ElMessage.error(res.msg || '密码重置失败')
    }
  } catch (error) {
    console.error('密码重置失败:', error)
    ElMessage.error('密码重置失败')
  }
}

// 修改 onMounted 钩子函数
onMounted(async () => {
  loading.value = true
  try {
    await fetchUserDetail()
  } catch (error) {
    console.error('初始化失败:', error)
  } finally {
    loading.value = false
  }
})

</script>

<style scoped>
@import '@/assets/css/user/edit.css';
@import '@/assets/css/header/index.css';

.form-actions .active {
  background-color: #909399;
  border-color: #909399;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.form-row {
  display: flex;
  margin-bottom: 15px;
  gap: 20px;
}

.form-row .el-form-item {
  flex: 1;
  margin-bottom: 0;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-form-item__label) {
  width: 100px !important;
  text-align: right;
}

:deep(.el-form-item__content) {
  margin-left: 10px !important;
}

.basic-info {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
}

.info-item span:first-child {
  font-weight: bold;
  color: #333;
  margin-right: 10px;
  width: 80px;
  text-align: right;
}

.edit-form {
  background-color: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  margin: 0 auto;
}
</style>